package com.example.client;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.net.InetSocketAddress;

public class NetworkChannel {
    private SocketChannel socketChannel;
    private String serverAddress;
    private int serverPort;

    // 构造方法，初始化服务器地址和端口
    public NetworkChannel(String serverAddress, int serverPort) {
        this.serverAddress = serverAddress;
        this.serverPort = serverPort;
        connect();
    }

    // 连接到服务器
    private void connect() {
        try {
            this.socketChannel = SocketChannel.open(new InetSocketAddress(serverAddress, serverPort));
            this.socketChannel.configureBlocking(false); // 设置为非阻塞模式
        } catch (IOException e) {
            System.err.println("连接服务器失败: " + e.getMessage());
        }
    }

    // 发送数据
    public void sendData(String data) {
        if (this.socketChannel == null) {
            System.err.println("未连接到服务器");
            return;
        }

        try {
            ByteBuffer buffer = ByteBuffer.wrap(data.getBytes());
            socketChannel.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 接收数据
    public String receiveData() {
        if (this.socketChannel == null) {
            System.err.println("未连接到服务器");
            return null;
        }

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            int bytesRead = socketChannel.read(buffer);
            if (bytesRead != -1) {
                return new String(buffer.array(), 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 关闭连接
    public void close() {
        if (this.socketChannel != null) {
            try {
                this.socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
